﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Project.Entitys;
using Modules.System.User;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Entity;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Project.Repositories;

/// <summary>
/// 项目参建企业非正常工资单授权仓储
/// </summary>
[UseDI(ServiceLifetime.Scoped)]
public class ProjectCorpWageAuthRepository : Repository<ProjectCorpWageAuth, DefaultDbContext>
{
    private readonly IApplicationContext applicationContext;
    public ProjectCorpWageAuthRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
    {

        this.applicationContext = applicationContext;
    }

    public IPagedList<ProjectCorpWageAuth> GetProjectCorpWageAuths(ProjectCorpWageAuthQuery query, int pageIndex, int pageSize)
    {
        Sql sql = Sql.Builder;
        sql.Select("id")
            .From("project_corp_wage_auth");
        #region 主管单位数据权限
        if (applicationContext.CurrentUser is IDeptUser deptUser && !deptUser.IsSuperAdministrator())
        {
            sql.InnerJoin("project as prj").On($"project_corp_wage_auth.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type=@0 ", deptUser.IndustryType);
            if (deptUser.Level == AdministrativeLevel.City)
                sql.Append($" and prj.city_code={deptUser.CityCode}");
            if (deptUser.Level == AdministrativeLevel.Area)
                sql.Append($" and prj.area_code={deptUser.AreaCode}");
        }
        #endregion
        if (query.ProjectId.HasValue)
            sql.Where("project_corp_wage_auth.project_id =@0", query.ProjectId);
        if (query.CorpId.HasValue)
            sql.Where("corp_id =@0", query.CorpId);
        if (!string.IsNullOrEmpty(query.Keywords))
            sql.Where("project_corp_wage_auth.project_id in (select id from project where name like @0 or prj_num like @0)  ", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
        sql.OrderBy("project_corp_wage_auth.create_time DESC");
        return GetPagingEntities(pageSize, pageIndex, sql);
    }

    public IEnumerable<ProjectCorpWageAuth> GetProjectCorpWageAuthByProjectId(int projectId)
    {
        int areaVersion = EntityCacheService.GetAreaVersion("ProjectId", projectId);
        return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
        {
            return $"ProjectCorpWageAuthByProjectId:{projectId}:{areaVersion}";
        }, () =>
        {
            Sql sql = Sql.Builder
            .Select("id")
            .From("project_corp_wage_auth")
            .Where("project_id=@0", projectId);
            return sql;
        });
    }

    /// <summary>
    /// 当月是否存在非正常工资单
    /// </summary>
    /// <param name="projectId"></param>
    /// <param name="corpId"></param>
    /// <param name="month"></param>
    /// <returns></returns>
    public bool ExistsByProjetIdCorpIdMonth(int projectId,int corpId,int month)
    {
        return DbContext.Exists<ProjectCorpWageAuth>("project_id=@0 AND corp_id=@1 And month=@2", projectId, corpId, month);
    }
}